package life.kenny.community.controller;

import life.kenny.community.dto.CommentCreateDto;
import life.kenny.community.dto.CommentDTO;
import life.kenny.community.dto.ResultDTO;
import life.kenny.community.enums.CommentTypeEnums;
import life.kenny.community.exception.CustomizeErrorCode;
import life.kenny.community.model.Comment;
import life.kenny.community.model.User;
import life.kenny.community.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Jay
 * @date 2021/11/15 2:33 下午
 */
@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @ResponseBody
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    public Object commentPost(@RequestBody CommentCreateDto commentCreateDto,
                              HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        //是否登录用户
        if (user == null) {
            return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
        }
        //check out commentDto
        if (commentCreateDto == null && commentCreateDto.getContent() == null) {
            return ResultDTO.errorOf(CustomizeErrorCode.CONTENT_IS_EMPTY);
        }
        Comment comment = new Comment();
        comment.setParentId(commentCreateDto.getParentId());
        comment.setContent(commentCreateDto.getContent());
        comment.setType(commentCreateDto.getType());
        comment.setCommentator(user.getId());
        comment.setGmtCreate(System.currentTimeMillis());
        comment.setGmtModified(System.currentTimeMillis());
        comment.setLikeCount(0L);
        commentService.insert(comment, user);
        return ResultDTO.okOf();
    }

    @ResponseBody
    @RequestMapping(value = "/comment/{id}", method = RequestMethod.GET)
    public ResultDTO<List<CommentDTO>> comments(@PathVariable(name = "id") Long id) {
        List<CommentDTO> commentDTOS = commentService.listByCommentId(id, CommentTypeEnums.COMMENT.getType());
        System.out.println(commentDTOS.size());
        return ResultDTO.okOf(commentDTOS);
    }
}
